package com.admin.education.controllers.api.v1;

import com.admin.education.common.exceptions.BadRequestException;
import com.admin.education.common.openId.OpenIdAuthorize;
import com.admin.education.common.response.IResponseMessage;
import com.admin.education.common.response.ResponseMessage;
import com.admin.education.common.response.ResponseMessageWithData;
import com.admin.education.common.response.Result;
import com.admin.education.dataTransferObject.ServicesExcuteResult;
import com.admin.education.dataTransferObject.votes.Request.VotesRequest;
import com.admin.education.dataTransferObject.votes.VotesTransfer;
import com.admin.education.services.Interfaces.IVotesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.Callable;

@RestController
@RequestMapping("/v1/votes")
public class VotesController {
    @Autowired
    private IVotesService votesService;

    @GetMapping("{id}")
    public Callable<IResponseMessage> queryVotesById(@PathVariable Long id) {
        return () -> {
            IResponseMessage responseMessage = null;

            ServicesExcuteResult<VotesTransfer> result = this.votesService.queryVotesById(id);
            if (result.isSuccess()) {
                responseMessage = new ResponseMessageWithData<>(Result.Success, result.getData());
            } else {
                throw new BadRequestException(result.getErrorMessage());
            }
            return responseMessage;
        };
    }

    @PostMapping("{id}/ballots")
    @OpenIdAuthorize
    public Callable<IResponseMessage> ballots(@PathVariable Long id, @RequestBody List<VotesRequest> votesRequests, HttpServletRequest request) {
        return () -> {
            IResponseMessage responseMessage = null;
            String openIdHeader = request.getHeader("OpenId");

            ServicesExcuteResult result = this.votesService.ballots(id, openIdHeader, votesRequests);
            if (result.isSuccess()) {
                responseMessage = new ResponseMessage(Result.Success);
            } else {
                throw new BadRequestException(result.getErrorMessage());
            }
            return responseMessage;
        };
    }
}
